import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:get/get.dart';
import 'package:pdzs_app/entities/entities.dart';
import 'package:pdzs_app/utils/utils.dart';

class TokenController extends GetxController {
  // email的控制器
  final TextEditingController usernameController = TextEditingController();
  // 密码的控制器
  final TextEditingController passController = TextEditingController();
  final storage = const FlutterSecureStorage();
  late String _token;
  String get token => _token;

  Future login() async {
    // 这里写登录逻辑
    var response = await Https.instance.dio.post('/login/login', data: {
      // "username": usernameController.text,
      // "password": passController.text
      "username": 'test123',
      "password": 'test123'
    });
    var data = jsonDecode(response.data);
    if (data['code'] == 0) {
      Get.snackbar("警告", data['msg']);
      return false;
    }
    var token = Token.fromJson(data);

    _token = token.data!.token!;
    await storage.write(key: "token", value: _token);
    return true;
  }

  Future logout() async {
    // 删除 token
    await storage.delete(key: "token");
    _token = '';
  }

  Future checkLogin() async {
    // 从 storage 中获取 token，判断是否已登录
    _token = (await storage.read(key: "token"))!;
    return _token != '';
  }
}
